import { findAppByRoute } from '../utils/index'
import { getMainLifecycle } from '../const/mainLifeCycle'
import { loadHtml } from '../loader/index'

export const lifecycle = async () => {
    // 获取到上一个子应用
    const prevApp = findAppByRoute(window.__ORIGIN_APP__);

    // 获取到要跳转到的子应用
    const nextApp = findAppByRoute(window.__CURRENT_SUB_APP__);
    console.log('nextApp', nextApp)
    if (!nextApp) {
        return
    }
    // 有上一个子应用 进行销毁
    if (prevApp && prevApp.destroyed) {
        await destroyed(prevApp)
    }
    const app = await beforeLoad(nextApp);
    await mounted(app)
}
export const beforeLoad = async (app: any) => {
    await runMainLifeCycle('beforeLoad')
    app && app.beforeLoad && app.beforeLoad()

    const subApp = await loadHtml(app)     // 获取子应用所有页面
    subApp && subApp.beforeLoad && subApp.beforeLoad()
    return subApp
}
export const mounted = async (app: any) => {
    app && app.mount && app.mount()
    await runMainLifeCycle('mounted')
}
export const destroyed = async (app: any) => {
    app && app.destroyed && app.destroyed();
    await runMainLifeCycle('destroyed')
}
export const runMainLifeCycle = async (type: any) => {
    const mainLeft: any = getMainLifecycle()
    await Promise.all(mainLeft[type].map(async (item: any) => await item()))
}
